package org.jeecg.modules.fund.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ExecutorBuilder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.fund.entity.FundAchievement;
import org.jeecg.modules.fund.entity.FundLibrary;
import org.jeecg.modules.fund.mapper.FundAchievementMapper;
import org.jeecg.modules.fund.service.IFundAchievementService;
import org.jeecg.modules.fund.service.IFundLibraryService;
import org.jeecg.modules.fund.service.IFundValueService;
import org.jeecg.modules.fund.util.FundAchievementUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
@Service
public class FundAchievementServiceImpl extends ServiceImpl<FundAchievementMapper, FundAchievement> implements IFundAchievementService {
    @Autowired
    private IFundLibraryService fundLibraryService;
    public static final String YEAR_TYPE = "年度业绩";
    public static final String JD_TYPE = "阶段业绩";
    public static final String YJ_TYPE_TITLE = "业绩类型";

    /**
     * 生成业绩数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create() {
        ExecutorService executorService = ExecutorBuilder.create().setCorePoolSize(8).setWorkQueue(new LinkedBlockingQueue<>(100)).build();
        log.info("==============执行【基金业绩】更新任务=============");
        log.info("【基金业绩】开始时间：" + DateUtil.now());
        // 根据规则获取代码
        List<FundLibrary> codeList = fundLibraryService.list(new QueryWrapper<FundLibrary>()
                .select("RIGHT(code,2) as 'code'")
                .groupBy("RIGHT(code,2)"));

        for (int i = 0; i < codeList.size(); i++) {
            // 批次号
            final int taskId = i;
            // 分类代码
            String categoryCode = codeList.get(i).getCode();
            // 根据code获取分类的基金列表
            List<FundLibrary> fundLibraryList = fundLibraryService.list(new QueryWrapper<FundLibrary>()
                    .ne("type", "货币型")
                    .eq("RIGHT(code,2)", categoryCode));
            // 线程池
            executorService.submit(() -> {
                // 构造参数列表
                List<FundAchievement> fundAchievementList = new ArrayList<>();
                // 遍历
                for (FundLibrary library : fundLibraryList){
                    // 获取远程数据
                    JSONArray httpData = FundAchievementUtil.getHttpData(library.getCode());
                    // 数据处理
                    if(httpData != null && !httpData.isEmpty()){
                        httpData.forEach(data -> {
                            // 构造数据
                            FundAchievement achievement = new FundAchievement().setFundId(library.getId());
                            // 转换
                            JSONObject jsonObject = JSONObject.parseObject(data.toString());
                            if (YEAR_TYPE.equals(jsonObject.getString(YJ_TYPE_TITLE))){
                                // 年度业绩
                                achievement.setType("year-type");
                                switch (jsonObject.getString("周期")){
                                    case "成立以来":
                                        achievement.setSort(0);
                                        break;
                                    case "今年以来":
                                        achievement.setSort(1);
                                        break;
                                    default:
                                        achievement.setSort(-jsonObject.getInteger("周期"));
                                        break;
                                }
                            } else {
                                // 阶段业绩
                                achievement.setType("stage-type");
                                switch (jsonObject.getString("周期")){
                                    case "近1月":
                                        achievement.setSort(1);
                                        break;
                                    case "近3月":
                                        achievement.setSort(2);
                                        break;
                                    case "近6月":
                                        achievement.setSort(3);
                                        break;
                                    case "近1年":
                                        achievement.setSort(4);
                                        break;
                                    case "近3年":
                                        achievement.setSort(5);
                                        break;
                                    case "近5年":
                                        achievement.setSort(6);
                                        break;
                                }
                            }
                            achievement.setSubType(jsonObject.getString("周期"));
                            achievement.setId(library.getId() + "-" +achievement.getType()  + "-" + achievement.getSubType() + "-" + achievement.getSort());
                            achievement.setFundSy(jsonObject.getBigDecimal("本产品区间收益"));
                            achievement.setFundHc(jsonObject.getBigDecimal("本产品最大回撒"));
                            achievement.setFundRank(jsonObject.getString("周期收益同类排名"));
                            achievement.setUpdateTime(new Date());
                            fundAchievementList.add(achievement);
                        });
                    }
                }
                if(!fundAchievementList.isEmpty()){
                    // 批量插入
                    this.saveOrUpdateBatch(fundAchievementList);
                }
                if(taskId == codeList.size() - 1){
                    log.info("【基金业绩】结束时间：" + DateUtil.now());
                }
            });
        }
    }
}
